package com.study.common.fdfs;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Component
public class ImageUtil {

    @Autowired
    private FastDFSClient fdfsClient;

    @Value("${fdfs.web-server-url}")
    private String fastdfsUrl;

    public String uploadFile (MultipartFile file){
        try {
            return  fdfsClient.uploadFile(file);
        }catch (Exception e){
            log.error("{}",e);
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param fileUrl  url 开头从组名开始
     * @throws Exception
     */

    public byte[] download(String fileUrl) throws Exception {

        return fdfsClient.download(fileUrl);
    }

    /**
     * 生成访问链接
     */
    public String location(String fileUrl) {
        StringBuilder str = new StringBuilder();
        str.append(fastdfsUrl);
        str.append(fileUrl);
//        fileUrl = getToken(fileUrl);
        return str.toString();
    }


    /**
     * 删除文侦探
     * @param fileUrl
     */
    public void deleteFile(String fileUrl) {

        //暂时没有用
        //fdfsClient.deleteFile(fileUrl);
    }
    /**
     * 替换前端全路径
     * @param fileUrl
     */
    public String replaceUrl(String fileUrl) {
        return fileUrl.replaceAll(fastdfsUrl, "");
    }
}
